package com.yigerende.web;



import com.yigerende.model.Blog;
import com.yigerende.model.Tag;
import com.yigerende.service.BlogService;
import com.yigerende.service.CommentService;
import com.yigerende.service.TagService;
import com.yigerende.service.TypeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.web.PageableDefault;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;

/**
 * 记住直接跳转页面用GetMapping，如果是表单提交方式用PostMapping
 * */
@Controller
public class IndexController {

    @Autowired
    private BlogService blogService;

    @Autowired
    private TypeService typeService;

    @Autowired
    private TagService tagService;

    @Autowired
    private CommentService commentService;

    @GetMapping("/")
    public String index(@PageableDefault(size = 10,sort = {"updateTime"},direction = Sort.Direction.DESC)
                                    Pageable pageable, Model model){
        //拿到左边分页的内容
        model.addAttribute("page",blogService.listBlog(pageable));
        //右边分类，标签，最新推荐
        model.addAttribute("types",typeService.listTypeTop(6));//传入一页最多要显示多少条分类
        model.addAttribute("tags",tagService.listTagTop(10));//传入一页最多要显示多少条标签
        model.addAttribute("recommendBlogs",blogService.listRecommendBlogTop(8));//传入一页最多要显示多少条推荐
        //拿到index页面要显示的所有数据了，现在在前端来显示要显示的数据
        return "index";
    }


    @PostMapping("/search")
    public String search(@PageableDefault(size = 7,sort = {"updateTime"},direction = Sort.Direction.DESC)
                                Pageable pageable, @RequestParam String query, Model model){
        //拿到query用户输入要查询的数据，可以是标题也可以是内容进行查询
        model.addAttribute("page",blogService.listBlog("%"+query+"%",pageable));
        //把查询的字符串返回到页面搜索框里面
        model.addAttribute("query",query);
        return "search";
    }

    //博客详情
    @GetMapping("/blog/{id}")
    public String blog(@PathVariable Long id, Model model){
        //通过传递过来的id进行查询放到blog里面
        model.addAttribute("blog",blogService.getAndConvert(id));
        //当条转博客详情页的时候也刷新评论
        model.addAttribute("comments",commentService.listCommentByBlogId(id));
        return "blog";
    }

    //关于我
    @GetMapping("/about")
    public String about(){
        return "about";
    }


    //刷新模板底部最新博客
    @GetMapping("/footer/newblog")
    public String newBlogs(Model model){
        model.addAttribute("newBlogs",blogService.listRecommendBlogTop(3));//传入一页最多要显示多少条推荐
        return "_fragments :: newblogList";
    }

}
